class Solution
{
    int n, m;
    int dx[4] = { 0, 0, -1, 1 }, dy[4] = { 1, -1, 0, 0 };
    int vis[1010][1010] = { -1 };

    int dfs(int i, int j, vector<vector<int> >& matrix)
    {
        if (vis[i][j] != -1) return vis[i][j];
        int len = 1;
        for (int k = 0; k < 4; k++)
        {
            int x = dx[k] + i, y = dy[k] + j;
            if (x >= 0 && y >= 0 && x < n && y < m && matrix[x][y] > matrix[i][j])
            {
                len = max(len, 1 + dfs(x, y, matrix));
            }
        }
        vis[i][j] = len;
        return len;
    }
public:
    int solve(vector<vector<int> >& matrix)
    {
        n = matrix.size(), m = matrix[0].size();
        memset(vis, -1, sizeof(vis));
        int ret = 1;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                ret = max(ret, dfs(i, j, matrix));
            }
        }
        return ret;
    }
};